Page({
  data: {
    userRole: 'student',
    semesters: ['2024-2025学年第一学期', '2024-2025学年第二学期', '2023-2024学年第一学期', '2023-2024学年第二学期'],
    currentSemesterIndex: 0,
    isLoading: true,
    
    // 学生成绩数据
    studentGrades: [],
    
    // 成绩统计
    gradeStats: {
      totalCredit: 0,
      averageScore: 0,
      averageGPA: 0,
      passRate: '0%'
    }
  },
  
  onLoad: function() {
    // 获取用户角色
    const app = getApp();
    if (app.globalData.userInfo && app.globalData.userInfo.role) {
      this.setData({
        userRole: app.globalData.userInfo.role
      });
    }
    // 获取成绩数据
    this.fetchGradeData();
  },
  
  onShow: function() {
    // 页面显示时刷新数据
    this.fetchGradeData();
  },
  
  // 获取成绩数据
  fetchGradeData: function() {
    // 显示加载状态
    this.setData({ isLoading: true });
    
    wx.showLoading({
      title: '加载成绩数据...',
    });
    
    const semester = this.data.semesters[this.data.currentSemesterIndex];
    
    wx.request({
      url: 'http://localhost:3000/api/grades/student',
      method: 'GET',
      data: {
        semester: semester
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          this.setData({
            studentGrades: res.data.grades || [],
            isLoading: false
          });
          // 计算成绩统计
          this.calculateGradeStats();
        } else {
          this.setData({
            isLoading: false
          });
          wx.showToast({
            title: res.data.message || '获取成绩数据失败',
            icon: 'none'
          });
          
          // 如果获取失败，使用模拟数据
          const mockData = this.getMockData();
          this.setData({
            studentGrades: mockData.grades
          });
          this.calculateGradeStats();
        }
      },
      fail: () => {
        wx.hideLoading();
        this.setData({
          isLoading: false
        });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        
        // 如果请求失败，使用模拟数据
        const mockData = this.getMockData();
        this.setData({
          studentGrades: mockData.grades
        });
        this.calculateGradeStats();
      }
    });
  },
  
  // 获取模拟数据
  getMockData: function() {
    return {
      grades: [
        {
          id: 1,
          courseName: '高等数学',
          credit: 4,
          score: 85,
          gpa: 3.7,
          teacher: '张教授',
          examType: '考试'
        },
        {
          id: 2,
          courseName: '大学英语',
          credit: 3,
          score: 92,
          gpa: 4.0,
          teacher: '李教授',
          examType: '考试'
        },
        {
          id: 3,
          courseName: '数据结构',
          credit: 4,
          score: 78,
          gpa: 3.3,
          teacher: '王教授',
          examType: '考试'
        },
        {
          id: 4,
          courseName: '计算机网络',
          credit: 3,
          score: 88,
          gpa: 3.7,
          teacher: '赵教授',
          examType: '考试'
        },
        {
          id: 5,
          courseName: '体育',
          credit: 1,
          score: 95,
          gpa: 4.0,
          teacher: '孙教练',
          examType: '考查'
        }
      ]
    };
  },
  
  // 切换学期
  changeSemester: function(e) {
    const semesterIndex = e.detail.value;
    this.setData({
      currentSemesterIndex: semesterIndex,
      isLoading: true
    });
    
    // 根据选择的学期获取成绩数据
    this.fetchGradeData();
  },
  
  // 计算学生成绩统计
  calculateGradeStats: function() {
    const grades = this.data.studentGrades;
    
    if (grades.length === 0) {
      this.setData({
        gradeStats: {
          totalCredit: 0,
          averageScore: 0,
          averageGPA: 0,
          passRate: '0%'
        }
      });
      return;
    }
    
    // 计算总学分
    const totalCredit = grades.reduce((sum, grade) => sum + parseFloat(grade.credit || 0), 0);
    // 计算加权平均分
    const weightedScoreSum = grades.reduce((sum, grade) => sum + parseFloat(grade.score || 0) * parseFloat(grade.credit || 0), 0);
    const averageScore = (weightedScoreSum / totalCredit).toFixed(1);
    // 计算平均GPA
    const weightedGPASum = grades.reduce((sum, grade) => sum + parseFloat(grade.gpa || 0) * parseFloat(grade.credit || 0), 0);
    const averageGPA = (weightedGPASum / totalCredit).toFixed(2);
    // 计算及格率
    const passCount = grades.filter(grade => parseFloat(grade.score || 0) >= 60).length;
    const passRate = (passCount / grades.length * 100).toFixed(0) + '%';
    
    this.setData({
      gradeStats: {
        totalCredit,
        averageScore,
        averageGPA,
        passRate
      }
    });
  },
  
  // 显示成绩详情
  showGradeDetail(e) {
    const grade = e.currentTarget.dataset.grade;
    this.setData({
      showDetailModal: true,
      currentGrade: grade
    });
  },

  // 隐藏成绩详情
  hideGradeDetail() {
    this.setData({
      showDetailModal: false,
      currentGrade: null
    });
  }
});